package com.zyz.common.security.service;

import com.zyz.common.core.constants.CacheConstants;
import com.zyz.common.core.constants.HttpConstants;
import com.zyz.common.core.constants.JwtConstants;
import com.zyz.common.redis.service.RedisService;
import com.zyz.common.core.model.LoginUser;
import com.zyz.common.core.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
public class TokenService {

    @Autowired
    private RedisService redisService;

    public String createToken(Long userId,String secret,Integer identity,String nickName,String headImage) {
        Map<String, Object> claim = new HashMap<>();
        // 生成唯一标识 用来关联redis数据
        String uuid = UUID.randomUUID().toString().replace("-", "");
        claim.put(JwtConstants.LOGIN_USER_ID, userId);
        claim.put(JwtConstants.LOGIN_USER_UUID, uuid);
        // 生成token
        String token = JwtUtil.createToken(claim, secret);
//        log.error("token:{}",token);
        // 使用redis存储敏感信息信息
        String key = getTokenKey(uuid);
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(key, loginUser, CacheConstants.LOGIN_TOKEN_TIMEOUT, TimeUnit.MINUTES); // 10h 过期
        // 返回token
        return token;
    }

    // 身份认证之后，请求到达controller之前进行延长
    public void extendTokenTime(String token, String secret) {

        String userUUID = getUserUUID(token, secret);
        // 拼接redis中的key
        String key = getTokenKey(userUUID);
        // 查询redis中key的过期时间
        long expire = redisService.getExpire(key, TimeUnit.MINUTES);
        if ( expire < CacheConstants.LOGIN_REFRESH_TIMEOUT) {
            // 进行延时
            redisService.expire(key,CacheConstants.LOGIN_TOKEN_TIMEOUT, TimeUnit.MINUTES);
        }
    }

    public LoginUser getLoginUser(String token, String secret) {
        String userUUID = getUserUUID(token, secret);
        if (!StringUtils.hasLength(userUUID)) {
            return null;
        }
        // 通过UUID查询redis中用户数据
        return redisService.getCacheObject(getTokenKey(userUUID),LoginUser.class);
    }

    public boolean deleteUserInfo(String token, String secret) {
        // 获取token中的uuid
        String userUUID = getUserUUID(token, secret);
        if (!StringUtils.hasLength(userUUID)) {
            return false;
        }
        // userUUID不为空，返回删除结果
        return redisService.deleteObject(getTokenKey(userUUID));
    }

    public Long getUserId (String token, String secret) {
        Claims claims = getClaims(token, secret);
        if (claims == null) return null;
        return JwtUtil.getUserId(claims);
    }

    public void refreshUserInfo(String nickName, String headImage, String tokenKey) {
        LoginUser cacheLoginUser = redisService.getCacheObject(tokenKey, LoginUser.class);
        cacheLoginUser.setHeadImage(headImage);
        cacheLoginUser.setNickName(nickName);
        redisService.setCacheObject(tokenKey,cacheLoginUser,CacheConstants.LOGIN_TOKEN_TIMEOUT, TimeUnit.MINUTES);
    }

    public String getTokenKey(String userUUID) {
        return CacheConstants.LOGIN_TOKEN_KEY + userUUID;
    }

    public String getUserUUID(String token, String secret) {
        Claims claims = getClaims(token, secret);
        if (claims == null) return null;
        return JwtUtil.getUserUUID(claims); //获取jwt中的key（uuid）
    }

    private static Claims getClaims(String token, String secret) {
        Claims claims;
        try {
            if (token.startsWith(HttpConstants.PREFIX)) {
                token = token.replace(HttpConstants.PREFIX, "");
            }
            claims = JwtUtil.parseToken(token, secret); //获取令牌中信息 解析payload中信息
            if (claims == null) {
                log.error("解析token出现异常1,token: {}", token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token出现异常2,token: {}", token);
            return null;
        }
        return claims;
    }





}
